STK.register('PhotoCollection', function() {

	var Backbone = STK.backbone,
	model = STK.PhotoModel,
    liwidth = 66,
    fixleft = 25,
    picroot = 'http://ww1.sinaimg.cn/';

	var PhotoCollection = Backbone.Collection.extend({
		model: model,
		getAlbum: function(n, key) {
			var self = this,
            data = this.model.get('data'),
			name = decodeURIComponent(n),
			ret,
			Albums = new Backbone.Collection(data);
			Albums.forEach(function(album) {
				var albumname = album.get('name');
				if (albumname == name) {
                    var Photos = new Backbone.Collection(album.get('detail')),
                        index = 0,
                        photo = Photos.find(function(photo){
                            if(photo.get('key') == key){
                                return photo;
                            }else{
                                index++;
                                return false;
                            }
                        });
                    if(photo){
                        var ulwidth = Photos.length * liwidth,
                            left =  index * liwidth;
                        left = self._fixleft(left,ulwidth);
                        album.set('bigpic',picroot+'large/'+key);
                        album.set('page','<em id="J_Slide_curnum">'+(index+1)+'</em>/'+Photos.length);
                        album.set('left',- left);
                        album.set('width',ulwidth);
                        album.set('index',index);
                        album.get('detail').forEach(function(item){
                            var itemkey = item.key;
                            if(itemkey == key) item.cls = 'special';
                            else item.cls = '';
                            item.smallpic = picroot+'small/'+itemkey;
                        });
					    ret = album;
					    return false;
                    }
				}
			});
			return ret;
		},
        _fixleft:function(left,ulwidth){
            var ww = $(window).width(),
                size = (ulwidth - ww) / liwidth;
            if(left >= ulwidth - ww && parseInt(size,10) != size) left = (Math.ceil(size) * liwidth) + fixleft;
            if(ww > ulwidth) left = 0;
            return left;
        },
        findIndexLeft:function(key,photos,fix){
            var left,ulwidth = photos.length * liwidth;
            for(var i=0;i<photos.length;i++){
                if(photos[i]['key'] == key){
                    left = i * liwidth;
                    if(!fix) left = this._fixleft(left,ulwidth,i);
                    return left;
                }
            }
            return left;
        }
	});

	return new PhotoCollection();

});

